package com.itheima.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itheima.service.UserService;

@Controller
public class UserController {
	
	private UserService userService;

	@RequestMapping("/hello")
	@ResponseBody
	public String helloWorld() {
		return "Hello World!!";
	}
	
	@RequestMapping("/add")
	public String addUser() {
		return "/user/add";
	}
	
	@RequestMapping("/update")
	public String updateUser() {
		return "/user/update";
	}
	
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "login";
	}
	
	//测试thymeleaf
	@RequestMapping("/testThymeleaf")
	public String testThymeleaf(Model model) {
		model.addAttribute("name", "贾宝玉");
		return "test";
	}
	
	
	/**
	 * 登录逻辑处理
	 */
	@RequestMapping("/login")
	public String login(String name ,String password ,Model model) {
		
		/*
		 * 编写认证操作
		 */
		//1.得到subject
		Subject subject = SecurityUtils.getSubject();
		
		//2.封装 用户数据
		UsernamePasswordToken token = new UsernamePasswordToken(name, password);
		
		//3.执行登录操作
		
		try {
			subject.login(token);
			//只要没有任何异常 就代表登录成功 否则就是失败
			//跳转到test.html
			return "redirect:/testThymeleaf";
		} catch (UnknownAccountException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			//登录失败
			model.addAttribute("msg", "用户名不存在");
			return "login";
		} catch (IncorrectCredentialsException e) {	
			//登录失败
			model.addAttribute("msg", "密码错误");
			return "login";
		}
		
	}
	
	//授权跳转页面
	@RequestMapping("/noAuth")
	public String toAuth() {
		return "noAuth";
	}
	
}
